﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Windows.Forms;
using DevExpress.Utils;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using DevExpress.XtraLayout.Utils;
using DevExpress.XtraTreeList;
using NNS.Framework;
using NNS.UI;
using QLTB.BusinessLayer;
using QLTB.BusinessObjects;
using QLTB.Common;
using QLTB.DataAccess;
using QLTB.ThietBi.Entity;

namespace QLTB.DieuChuyen.UI
{
    [System.ComponentModel.ToolboxItem(false)]
    public partial class ucDieuChuyen : MyUIBase
    {
        private GridHitInfo downhitInfo;
        private DataTable dtTL;
        private int madv;

        public ucDieuChuyen()
        {
            InitializeComponent();
            gbList.BestFitColumns();
            NapInf();
            txtDonvi.EditValue = MyLogin.Original.iddonvi;
            if (!MyLogin.Original.toantinh)
            {
                txtDonvi.Enabled = false;
                txtDonvi.EditValue = MyLogin.Original.iddonvi;
            }

            TBL_quyenBL.IgnoreError = true;
            if (!TBL_quyenBL.isTaomoi(EnumComponent.iEquipmentTransfer))
            {
                btnAllRight.Visible = false;
                btnRight.Visible = false;
            }
            TBL_quyenBL.IgnoreError = false;
        }

        private void view_MouseDown(object sender, MouseEventArgs e)
        {
            var view = sender as GridView;
            downhitInfo = null;
            GridHitInfo hitInfo = view.CalcHitInfo(new Point(e.X, e.Y));
            if (ModifierKeys != Keys.None) return;
            downhitInfo = gbList.CalcHitInfo(new Point(e.X, e.Y));
            if (e.Button == MouseButtons.Left && hitInfo.RowHandle >= 0)
            {
                downhitInfo = hitInfo;
            }
        }

        private void view_MouseMove(object sender, MouseEventArgs e)
        {
            var view = sender as GridView;
            if (e.Button == MouseButtons.Left && downhitInfo != null)
            {
                Size dragSize = SystemInformation.DragSize;
                var dragRect =
                    new Rectangle(
                        new Point(downhitInfo.HitPoint.X - dragSize.Width/2, downhitInfo.HitPoint.Y - dragSize.Height/2),
                        dragSize);
                if (!dragRect.Contains(new Point(e.X, e.Y)))
                {
                    if (downhitInfo.RowHandle >= 0)
                    {
                        DataRow row = view.GetDataRow(downhitInfo.RowHandle);
                        view.GridControl.DoDragDrop(row, DragDropEffects.Move);
                        downhitInfo = null;
                        DXMouseEventArgs.GetMouseArgs(e).Handled = true;
                    }
                }
            }
        }


        //</gridControl1>

        public void Nap()
        {
            try
            {
                NotSave = false;
                tBL_THIETBITableAdapter.Connection.ConnectionString = DbHelper.ConnectionString;
                if (txtDonvi.EditValue != null)
                    tBL_THIETBITableAdapter.FillBy(dsThietBi.TBL_THIETBI, txtDonvi.EditValue as int?);
            }
            catch (Exception ex)
            {
                MyBox.ShowWarning(ex.Message, "Thanh lý");
            }
        }

        public void NapInf()
        {
            try
            {
                tBL_DONVITableAdapter.Connection.ConnectionString = DbHelper.ConnectionString;
                tBL_DONVITableAdapter.Fill(dsDonVi.TBL_DONVI);

                txtDonviden.Properties.DataSource = dsDonVi.TBL_DONVI;

                tlList.DataSource =  tBL_DONVITableAdapter.GetDataAll();
                tlList.ExpandAll();
            }
            catch (Exception ex)
            {
                MyBox.ShowWarning(ex.Message, "Thanh lý");
            }
            NapDTL();
        }

        public void NapDTL()
        {
            try
            {
                if (dtTL != null) dtTL.RowChanged -= dtTL_RowChanged;
                if (dtTL == null)
                {
                    tBL_THIETBITableAdapter.Connection.ConnectionString = DbHelper.ConnectionString;
                    gcDesc.DataSource = dtTL = new ThietBi.Entity.dsThietBi.TBL_THIETBIDataTable();
                }
                dtTL.RowChanged += dtTL_RowChanged;
            }
            catch (Exception ex)
            {
                MyBox.ShowWarning(ex.Message, "Thanh lý");
            }
        }

        private void dtTL_RowChanged(object sender, DataRowChangeEventArgs e)
        {
            NotSave = true;
        }

        private void txtDonvi_EditValueChanged(object sender, EventArgs e)
        {
            Nap();
            NapDTL();
        }

        private void Grid_DragOver(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(typeof (dsThietBi.TBL_THIETBIRow)))
            {
                e.Effect = DragDropEffects.Move;
            }
            else
                e.Effect = DragDropEffects.None;
        }

        private void Grid_DragDrop(object sender, DragEventArgs e)
        {
            var grid = sender as GridControl;
            var table = grid.DataSource as DataTable;
            if (table == null)
            {
                table = dsThietBi.TBL_THIETBI;
            }
            var row = e.Data.GetData(typeof (dsThietBi.TBL_THIETBIRow)) as DataRow;

            if (row != null && table != null && row.Table != table)
            {
                table.ImportRow(row);
                row.Delete();
            }
        }

        private void gbList_DoubleClick(object sender, EventArgs e)
        {
            //GridControl grid = sender as GridControl;
            var table = gcDesc.DataSource as DataTable;
            int[] rows = gbList.GetSelectedRows();
            for (int i = rows.Length; i > 0; i--)
            {
                DataView dv;
                dv = gbDesc.DataSource as DataView;
                DataRow dr = gbList.GetDataRow(rows[i - 1]);
                dv.RowFilter = "ID=" + dr["ID"];
                if (dv.Count == 0)
                {
                    table.ImportRow(dr);
                }
                gbList.DeleteRow(rows[i - 1]);
                dv.RowFilter = "";
            }
        }

        private void view_DoubleClick(object sender, EventArgs e)
        {
            var view = sender as GridView;
            var table = view.DataSource as DataTable;
            int[] rows = gbList.GetSelectedRows();
            for (int i = rows.Length; i > 0; i--)
            {
                DataView dv;
                dv = gbDesc.DataSource as DataView;
                DataRow dr = gbList.GetDataRow(rows[i - 1]);
                dv.RowFilter = "ID=" + dr["ID"];
                if (dv.Count == 0)
                {
                    table.ImportRow(dr);
                    gbList.DeleteRow(rows[i - 1]);
                }
                dv.RowFilter = "";
            }
        }


        private void view_Delete(object sender, KeyEventArgs e)
        {
            if (!TBL_quyenBL.isThaydoi(EnumComponent.iEquipmentTransfer))
            {
                return;
            }

            var view = sender as GridView;
            if (e.KeyCode == Keys.Delete)
            {
                view.DeleteSelectedRows();
            }
            else if (e.KeyData == (Keys.Control | Keys.Enter))
            {
                if (view == gbList)
                {
                    gbList_DoubleClick(gbList, e);
                }
                else
                {
                    gbDesc_DoubleClick(gbDesc, e);
                }
            }
            else if (e.KeyData == (Keys.Control | Keys.Right))
            {
                gbList_DoubleClick(gbList, e);
            }
            else if (e.KeyData == (Keys.Control | Keys.Left))
            {
                gbDesc_DoubleClick(gbDesc, e);
            }
        }

        public override void Save()
        {
            Enabled = false;
            Cursor current = Cursor.Current;
            Cursor.Current = Cursors.WaitCursor;

            try
            {
                var donvida = new TBL_DONVIDA();

                if (dtTL != null)
                    for (int i = 0; i < dtTL.Rows.Count; i++)
                    {
                       
                        DataRow dr = dtTL.Rows[i];
                        if (dr.RowState != DataRowState.Deleted)
                        {
                            //co ket noi den database
                            TBL_DONVI ob = donvida.Get((int) txtDonviden.EditValue);

                            SqlHelper.Helper.Start();

                            if (ob != null)
                            {
                                if (ob.MaCapTren != null)
                                {
                                    
                                    var donviquanly = (int) ob.MaCapTren;
                                    SqlHelper.Helper.ExecuteNonQuery( CommandType.Text,
                                                                     "update TBL_THIETBI set MaDonVi=@MaDonvi  where ID=@ID",
                                                                     new[]
                                                                         {
                                                                             new SqlParameter("@ID", dr["ID"]),
                                                                             new SqlParameter("@MaDonvi", donviquanly),
                                                                         });
                                    if (SqlHelper.HasError)
                                    {
                                        MyBox.ShowWarning(SqlHelper.Message, "Điểu Chuyển");
                                        SqlHelper.Helper.Destroy();
                                    }
                                }
                                else
                                {
                                    if (ob.CapDonvi==2)
                                    {
                                        SqlHelper.Helper.ExecuteNonQuery(CommandType.Text,
                                                                     "update TBL_THIETBI set MaDonVi=@MaDonvi  where ID=@ID",
                                                                     new[]
                                                                         {
                                                                             new SqlParameter("@ID", dr["ID"]),
                                                                             new SqlParameter("@MaDonvi", txtDonviden.EditValue),
                                                                         });
                                        if (SqlHelper.HasError)
                                        {
                                            MyBox.ShowWarning(SqlHelper.Message, "Điểu Chuyển");
                                            SqlHelper.Helper.Destroy();
                                        }
                                    }
                                }
                            }


                            if (chxThuhoi.Checked)
                            {
                                SqlHelper.Helper.ExecuteNonQuery( CommandType.Text,
                                                                 "update TBL_THIETBI set NoiSD=@MaDonvi,TinhTrang=@tinhtrang  where ID=@ID",
                                                                 new[]
                                                                     {
                                                                         new SqlParameter("@ID", dr["ID"]),
                                                                         new SqlParameter("@MaDonvi", madv),
                                                                         new SqlParameter("@tinhtrang", 1),
                                                                     });
                            }
                            else
                            {
                                SqlHelper.Helper.ExecuteNonQuery(CommandType.Text,
                                                                 "update TBL_THIETBI set NoiSD=@MaDonvi  where ID=@ID",
                                                                 new[]
                                                                     {
                                                                         new SqlParameter("@ID", dr["ID"]),
                                                                         new SqlParameter("@MaDonvi", madv),
                                                                     });
                            }

                            if (SqlHelper.Helper.LastError != null)
                            {
                                SqlHelper.Helper.Destroy();
                                MyBox.ShowWarning(SqlHelper.Helper.LastError.ToString(), "Điều Chuyển");
                            }

                            var da = new TBL_DieuChuyenDA();
                            da.Add(new TBL_DieuChuyen
                                       {
                                           GhiChu = txtGhiChu.Text,
                                           MaBCdi = (int) txtDonvi.EditValue,
                                           MaBCDen = madv,
                                           MaTB = (int) dr["ID"],
                                           Ngay = dtNgay.DateTime
                                       });

                            if (SqlHelper.Helper.LastError != null)
                            {
                                SqlHelper.Helper.Destroy();
                                MyBox.ShowWarning(SqlHelper.Helper.LastError.ToString(), "Điểu Chuyển");
                            }

                            var lichsuDa = new TBL_lichsuDA();
                            lichsuDa.Add(new TBL_lichsu
                                             {
                                                 idthietbi = (int) dr["ID"],
                                                 ngay = dtNgay.DateTime,
                                                 nguoiTH = MyLogin.Original.hoten,
                                                 noidung = "Điều chuyển thiết bị từ " + txtDonvi.Text + " đến " + txtDonviden.Text
                                             });

                            if (SqlHelper.HasError)
                            {
                                MyBox.ShowWarning(SqlHelper.Message, "Điều Chuyển");
                                SqlHelper.Helper.Destroy();
                            }

                            SqlHelper.Helper.Accept();
                        }

                        OnSaveChanging(new SaveChangingEventArgs(i, dtTL.Rows.Count));

                        btnSave.Enabled = false;
                    }
            }
            catch (Exception ex)
            {
                MyBox.ShowWarning(ex.Message, "Điều Chuyển");
                btnSave.Enabled = true;
            }
            
            NotSave = false;
            OnSaveComplete(null);
            Cursor.Current = current;
            Enabled = true;
        }

        private void gbDesc_DoubleClick(object sender, EventArgs e)
        {
            DataTable table = dsThietBi.TBL_THIETBI;
            int[] rows = gbDesc.GetSelectedRows();
            for (int i = rows.Length; i > 0; i--)
            {
                DataView dv = dsThietBi.TBL_THIETBI.DefaultView;
                DataRow dr = gbDesc.GetDataRow(rows[i - 1]);
                if (dv != null)
                {
                    dv.RowFilter = "ID=" + dr["ID"];
                    if (dv.Count == 0)
                    {
                        table.ImportRow(dr);
                    }
                    gbDesc.DeleteRow(rows[i - 1]);
                    dv.RowFilter = "";
                }
            }
        }

        public void Cancel()
        {
            dsThietBi.RejectChanges();
            NapDTL();
            NotSave = false;
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            Nap();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            Save();
        }

        private void tlList_FocusedNodeChanged(object sender, FocusedNodeChangedEventArgs e)
        {
            txtDonviden.EditValue = null;
            madv = 0;
            if (e.Node != null)
            {
                madv = (int) e.Node.GetValue("MaDonVi");
                txtDonviden.EditValue = madv;
            }
        }

        private void btnRight_Click(object sender, EventArgs e)
        {
            gbList_DoubleClick(gbList, e);
        }

        private void btnLeft_Click(object sender, EventArgs e)
        {
            gbDesc_DoubleClick(gbDesc, e);
        }

        private void btnAllRight_Click(object sender, EventArgs e)
        {
            gbList.SelectAll();
            gbList_DoubleClick(gbList, e);
        }

        private void btnAllLeft_Click(object sender, EventArgs e)
        {
            gbDesc.SelectAll();
            gbDesc_DoubleClick(gbDesc, e);
        }

        private void txtDonviden_EditValueChanged(object sender, EventArgs e)
        {
            if (txtDonviden.EditValue == null) return;
            var donvi = (int) txtDonviden.EditValue;
            liThuhoi.Visibility = LayoutVisibility.Never;
            chxThuhoi.Checked = false;
            if (donvi > 850100 && donvi < 851000)
            {
                liThuhoi.Visibility = LayoutVisibility.Always;
                chxThuhoi.Checked = true;
            }
        }

        public override void Add()
        {
            if (dtTL != null) dtTL.Rows.Clear();
            btnSave.Enabled = true;
        }
    }
}